package com.alibaba.citrus.cr.sales.plan.repository;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.citrus.cr.platform.enhance.repository.OrganizationRepository;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.NotificationConditionQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.NotificationConfigQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryNotificationConfigRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.MonthlyPlanDataSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.NotificationConfigSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.sdk.oss.EpochOssService;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.NotificationConfigLoadListRequest;
import com.epoch.app.bcorder.model.enums.NoticeTitle;
import com.epoch.app.bcorder.sales_plan.notificationconfig.dto.CreateNotificationConfigResponse;
import com.epoch.app.bcorder.sales_plan.notificationconfig.dto.LoadNotificationConfigRequest;
import com.epoch.app.bcorder.sales_plan.notificationconfig.dto.UpdateNotificationConfigResponse;
import com.epoch.app.bcorder.sales_plan.notificationconfig.model.NotificationConfig;
import com.epoch.app.bcorder.sales_plan.notificationconfig.service.NotificationConfigService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class NotificationConfigRepositoryImpl implements NotificationConfigRepository {

    private final static Log log = Log.getLogger(NotificationConfigRepositoryImpl.class);

    @Resource
    private NotificationConfigService notificationConfigService;

    @Resource
    private OrganizationRepository organizationRepository;

    @Resource
    private EpochOssService epochOssService;

    /**
     * 新增
     *
     * @param notificationConfigSDO
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public String save(NotificationConfigSDO notificationConfigSDO) {
        NotificationConfigLoadListRequest notificationConfigLoadListRequest = new NotificationConfigLoadListRequest();
        notificationConfigLoadListRequest.setBusinessUnitCode(notificationConfigSDO.getBusinessUnitCode());
        notificationConfigLoadListRequest.setTitle(notificationConfigSDO.getTitle());
        //当前模版类型只有5个，目前10条满足需求
        notificationConfigLoadListRequest.setLimit(10);
        NotificationConfig notificationConfig = new NotificationConfig();
        BeanUtils.copyProperties(notificationConfigSDO, notificationConfig);
        Result<List<NotificationConfig>> listResult = notificationConfigService.loadNotificationConfigList(notificationConfigLoadListRequest);
        List<NotificationConfig> result = listResult.getResult();
        for (NotificationConfig config : result) {
            if (config.getBusinessUnitCode() == null) {
                if (config.getTitle().equals(notificationConfigSDO.getTitle())) {
                    throw new FacadeException("OTS-07-005-01-16-007");
                }
                continue;
            }
            if (config.getBusinessUnitCode().equals(notificationConfigSDO.getBusinessUnitCode()) && config.getTitle().equals(notificationConfigSDO.getTitle())) {
                throw new FacadeException("OTS-07-005-01-16-007");
            }
        }
        notificationConfig.setRealTime(1);
        notificationConfig.setStatus(1);
        CreateNotificationConfigResponse configResponse = notificationConfigService.createNotificationConfig(notificationConfig);
        return configResponse.getLastInsertId();
    }


    /**
     * 分页查询
     *
     * @param pageQueryNotificationConfigRequest
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<NotificationConfigSDO>> pageQuery(
        PageQueryNotificationConfigRequest pageQueryNotificationConfigRequest) {
        NotificationConfigLoadListRequest notificationConfigLoadListRequest = notificationConfigQueryConverter(pageQueryNotificationConfigRequest);
        //查询所有（获取通用的）
//        notificationConfigLoadListRequest.setBusinessUnitCode(null);
        Result<List<NotificationConfig>> listResult = notificationConfigService.loadNotificationConfigList(notificationConfigLoadListRequest);
        log.error("wyd.listResult="+JSONObject.toJSONString(listResult));
        List<NotificationConfigSDO> notificationConfigSDOS = listResult.getResult().stream().map(notificationConfig -> {
            NotificationConfigSDO notificationConfigSDO = new NotificationConfigSDO();
            BeanUtils.copyProperties(notificationConfig, notificationConfigSDO);
            if (StringUtils.isNotBlank(notificationConfig.getTitle())) {
                notificationConfigSDO.setLabel(NoticeTitle.of(Integer.valueOf(notificationConfig.getTitle())).getLabel());
            }
            if (Objects.isNull(notificationConfig.getBusinessUnitCode()) && !notificationConfig.getTitle().equals("5")) {
                notificationConfigSDO.setName("通用");
                notificationConfigSDO.setRecipient("相关员工账号");
                return notificationConfigSDO;
            } else if (notificationConfig.getTitle().equals("5")) {
                notificationConfigSDO.setName("通用");
                return notificationConfigSDO;
            }
            OrganizationSDO organizationById = organizationRepository.getOrganizationById(notificationConfig.getBusinessUnitCode());
            if (organizationById == null) {
                throw new FacadeException("OTS-07-005-01-16-001");
            }
            notificationConfigSDO.setName(organizationById.getName());
            return notificationConfigSDO;
        }).collect(Collectors.toList());
        //如果bizType大于于103 那么什么都看不到
        if (pageQueryNotificationConfigRequest.getBizType() > OrganizationTypeEnum.COMPANY.getCode()) {
            return PageResult.of(Lists.newArrayList(), 0);
        }
        //如果bizType等于103 那么就看自己归属和通用
        if (pageQueryNotificationConfigRequest.getBizType().equals(OrganizationTypeEnum.COMPANY.getCode())) {
            List<NotificationConfigSDO> notificationConfigSDOS2 = new ArrayList<>();
//            log.error("wyd.notificationConfigSDOS="+JSONObject.toJSONString(notificationConfigSDOS));
            for (NotificationConfigSDO notificationConfigSDO : notificationConfigSDOS) {
                if (StringUtils.isBlank(notificationConfigSDO.getBusinessUnitCode()) ||
                        notificationConfigSDO.getBusinessUnitCode().equals(pageQueryNotificationConfigRequest.getBizId())) {
                    notificationConfigSDOS2.add(notificationConfigSDO);
                }
            }
            log.error("wyd.000.notificationConfigSDOS2="+JSONObject.toJSONString(notificationConfigSDOS2));
            //查询特定业务单元且title=1的数据
            if (null == pageQueryNotificationConfigRequest.getBusinessUnitCode()) {
                if (null == pageQueryNotificationConfigRequest.getTitle()) {
                    notificationConfigLoadListRequest.setTitle("1");
                }
                notificationConfigLoadListRequest.setBusinessUnitCode(pageQueryNotificationConfigRequest.getBizId());
                Result<List<NotificationConfig>> listResult1 = notificationConfigService.loadNotificationConfigList(notificationConfigLoadListRequest);
                log.error("wyd.listResult1="+JSONObject.toJSONString(listResult1));
                if (CollectionUtils.isNotEmpty(listResult1.getResult())) {
                    OrganizationSDO organization = organizationRepository.getOrganizationById(notificationConfigLoadListRequest.getBusinessUnitCode());
                    if (organization == null) {
                        throw new FacadeException("OTS-07-005-01-16-001");
                    }
                    List<NotificationConfigSDO> notificationConfigSDOList = listResult1.getResult().stream().map(notificationConfig -> {
                        NotificationConfigSDO notificationConfigSDO = new NotificationConfigSDO();
                        BeanUtils.copyProperties(notificationConfig, notificationConfigSDO);
                        if (StringUtils.isNotBlank(notificationConfig.getTitle())) {
                            notificationConfigSDO.setLabel(NoticeTitle.of(Integer.valueOf(notificationConfig.getTitle())).getLabel());
                        }
                        notificationConfigSDO.setName(organization.getName());
                        return notificationConfigSDO;
                    }).collect(Collectors.toList());
                    log.error("wyd.notificationConfigSDOList="+JSONObject.toJSONString(notificationConfigSDOList));
                    List<Long> list = notificationConfigSDOS2.stream().filter(Objects::nonNull).map(NotificationConfigSDO::getId).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(list)) {
                        List<NotificationConfigSDO> configSDOList = notificationConfigSDOList.stream().filter(o -> !list.contains(o.getId())).collect(Collectors.toList());
                        log.error("wyd.collect="+JSONObject.toJSONString(configSDOList));
                        notificationConfigSDOS2.addAll(configSDOList);
                        log.error("wyd.111.notificationConfigSDOS2="+JSONObject.toJSONString(notificationConfigSDOS2));
                    } else {
                        notificationConfigSDOS2.addAll(notificationConfigSDOList);
                        log.error("wyd.222.notificationConfigSDOS2="+JSONObject.toJSONString(notificationConfigSDOS2));
                    }
                }
            }
            log.error("wyd.333.notificationConfigSDOS2="+JSONObject.toJSONString(notificationConfigSDOS2));
            return PageResult.of(notificationConfigSDOS2, notificationConfigSDOS2.size());
        }
        //如果bizType小于103那么就都能看到
        return PageResult.of(notificationConfigSDOS, listResult.getTotal());

    }

    /**
     * 修改收件人  通知内容
     *
     * @param notificationConfigSDO
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean doEdit(NotificationConfigSDO notificationConfigSDO) {
        NotificationConfig notificationConfig = new NotificationConfig();
        BeanUtils.copyProperties(notificationConfigSDO, notificationConfig);
        Integer count1 = notificationConfigService.updateNotificationConfig(notificationConfig).getCount();
        if (count1 != 1) {
            throw new FacadeException("OTS-07-005-01-16-008");
        }
        return true;
    }

    /**
     * 修改状态
     *
     * @param notificationConfigSDO
     * @return
     */
    @Override
    @RepositoryInvoker(printLog = true)
    public Integer editNotificationConfig(NotificationConfigSDO notificationConfigSDO) {
        NotificationConfig notificationConfig = notificationConfigConverter(notificationConfigSDO);
        UpdateNotificationConfigResponse updateNotificationConfigResponse = notificationConfigService.updateNotificationConfig(notificationConfig);
        return updateNotificationConfigResponse.getCount();
    }


    @Override
    @RepositoryInvoker(printLog = true)
    public NotificationConfigSDO queryNotificationConfig(NotificationConfigQueryRequest configQueryRequest) {
        LoadNotificationConfigRequest loadNotificationConfigRequest = notificationConfigQueryRequestConverter(configQueryRequest);
        NotificationConfig notificationConfig = notificationConfigService.loadNotificationConfig(loadNotificationConfigRequest);
        NotificationConfigSDO notificationConfigSDO = new NotificationConfigSDO();
        BeanUtils.copyProperties(notificationConfig, notificationConfigSDO);
        return notificationConfigSDO;
    }


    private NotificationConfigLoadListRequest notificationConfigQueryConverter(PageQueryNotificationConfigRequest pageQueryNotificationConfigRequest) {
        NotificationConfigLoadListRequest loadListRequest = new NotificationConfigLoadListRequest();
        BeanUtils.copyProperties(pageQueryNotificationConfigRequest, loadListRequest);
        return loadListRequest;
    }

    private NotificationConfig notificationConfigConverter(NotificationConfigSDO notificationConfigSDO) {
        NotificationConfig notificationConfig = new NotificationConfig();
        BeanUtils.copyProperties(notificationConfigSDO, notificationConfig);
        return notificationConfig;
    }

    private LoadNotificationConfigRequest notificationConfigQueryRequestConverter(NotificationConfigQueryRequest configQueryRequest) {
        LoadNotificationConfigRequest loadNotificationConfigRequest = new LoadNotificationConfigRequest();
        loadNotificationConfigRequest.setId(Long.valueOf(configQueryRequest.getId()));
        return loadNotificationConfigRequest;
    }

    private NotificationConfigLoadListRequest notificationConditionQueryRequestConverter(
        NotificationConditionQueryRequest notificationConditionQueryRequest) {
        NotificationConfigLoadListRequest notificationConfigLoadListRequest = new NotificationConfigLoadListRequest();
        if (notificationConditionQueryRequest.getBusinessUnitCode() != null) {
            notificationConfigLoadListRequest.setBusinessUnitCode(notificationConditionQueryRequest.getBusinessUnitCode());
        }
        if (notificationConditionQueryRequest.getTitle() != null) {
            notificationConfigLoadListRequest.setTitle(notificationConditionQueryRequest.getTitle());
        }
        return notificationConfigLoadListRequest;
    }

    /**
     * 根据id查询发送邮件配置
     *
     * @param notificationConfigQueryRequest
     * @return
     */
    @Override
    public NotificationConfigSDO queryNotificationConfigById(NotificationConfigQueryRequest notificationConfigQueryRequest) {
        LoadNotificationConfigRequest loadNotificationConfigRequest = loadNotificationConfigConverter(notificationConfigQueryRequest);
        try {
            NotificationConfig notificationConfig = notificationConfigService.loadNotificationConfig(loadNotificationConfigRequest);
            OrganizationSDO organizationById = organizationRepository.getOrganizationById(notificationConfig.getBusinessUnitCode());
            NotificationConfigSDO notificationConfigSDO = new NotificationConfigSDO();
            notificationConfigSDO.setLabel(NoticeTitle.of(Integer.valueOf(notificationConfig.getTitle())).getLabel());
            notificationConfigSDO.setTitle(notificationConfig.getTitle());
            notificationConfigSDO.setContent(notificationConfig.getContent());
            if (notificationConfig.getRecipient().contains(";")) {
                //如果有多个收件人是用 ； 来分开
                String[] recipients = notificationConfig.getRecipient().split(";");
            }
            notificationConfigSDO.setRecipient(notificationConfig.getRecipient());
            notificationConfigSDO.setName(organizationById.getName());
            return notificationConfigSDO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private LoadNotificationConfigRequest loadNotificationConfigConverter(NotificationConfigQueryRequest notificationConfigQueryRequest) {
        LoadNotificationConfigRequest loadNotificationConfigRequest = new LoadNotificationConfigRequest();
        loadNotificationConfigRequest.setId(Long.valueOf(notificationConfigQueryRequest.getId()));
        return loadNotificationConfigRequest;
    }

    /**
     * 生成月度计划数据模板-Excel
     *
     * @param excelList
     * @return
     */
    @Override
    public void generateExcel(List<MonthlyPlanDataSDO> excelList, String fileName, String planTime) {
      /*  SimpleDateFormat str = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        String format = str.format(date);*/
        ObjectMetadata metadata = new ObjectMetadata();
        try {
            ExcelWriterBuilder workBook = EasyExcel.write(fileName, MonthlyPlanDataSDO.class);
            workBook.sheet().doWrite(excelList);
            //上传oss
            log.info("上传文件oss信息:{}，{}", BcOrderConstants.OSS_NAME(), BcOrderConstants.OSS_BUCKET());
            PutObjectResult oss = epochOssService.upload(BcOrderConstants.OSS_NAME(), BcOrderConstants.OSS_BUCKET(), new File(fileName), "salesPlan/adjustFile/" + planTime, metadata);
            log.info("上传oss返回结果:{}", JSONObject.toJSONString(oss));
        } catch (Exception e) {
            log.error("上传oss发生异常", e);
            throw new RepositoryException(ErrorMessage.code("OTS-02-005-00-16-010"));
        }
    }

    @Override
    public PageResult<List<NotificationConfigSDO>> pageQueryMailTemplate(PageQueryNotificationConfigRequest pageQueryNotificationConfigRequest) {
        NotificationConfigLoadListRequest notificationConfigLoadListRequest = notificationConfigQueryConverter(pageQueryNotificationConfigRequest);
        Result<List<NotificationConfig>> listResult = notificationConfigService.loadNotificationConfigList(notificationConfigLoadListRequest);
        List<NotificationConfigSDO> notificationConfigSDOS = listResult.getResult().stream().map(notificationConfig -> {
            NotificationConfigSDO notificationConfigSDO = new NotificationConfigSDO();
            BeanUtils.copyProperties(notificationConfig, notificationConfigSDO);
            if (StringUtils.isNotBlank(notificationConfig.getTitle())) {
                notificationConfigSDO.setLabel(NoticeTitle.of(Integer.valueOf(notificationConfig.getTitle())).getLabel());
            }
            if (Objects.isNull(notificationConfig.getBusinessUnitCode()) && !notificationConfig.getTitle().equals(NoticeTitle.Category_Maintenance.getValue().toString())) {
                notificationConfigSDO.setName("通用");
                notificationConfigSDO.setRecipient("相关员工账号");
                return notificationConfigSDO;
            } else if (notificationConfig.getTitle().equals(NoticeTitle.Category_Maintenance.getValue().toString())) {
                notificationConfigSDO.setName("通用");
                return notificationConfigSDO;
            }
            OrganizationSDO organizationById = organizationRepository.getOrganizationById(notificationConfig.getBusinessUnitCode());
            if (organizationById == null) {
                throw new FacadeException("OTS-07-005-01-16-001");
            }
            notificationConfigSDO.setName(organizationById.getName());
            return notificationConfigSDO;
        }).collect(Collectors.toList());
        return PageResult.of(notificationConfigSDOS, listResult.getTotal());
    }
}
